<template>
  <div class="app-container">
    <shipping-table
      :list="list"
      :total="total" 
      :list-loading="listLoading"
      :list-query="listQuery"
      :show-delete-filter="false"
      :show-search-input="false"
      @filter="handleFilter"
      @get-list="getList"
      @selection-change="handleSelectionChange"
      @pagination-change="handlePaginationChange"
    >
      <template #filter-items>
        <el-select
          v-model="listQuery.process"
          placeholder="处理方式"
          clearable
          class="filter-item"
          style="width: 120px"
          @change="handleProcessChange"
        >
          <el-option label="入成品仓" value="IN_PRODUCT" />
          <el-option label="回国维修" value="REPAIR" />
          <el-option label="报废" value="SCRAP" />
        </el-select>
      </template>
      
      <template #action-buttons="{ selection }">
        <el-button
          v-if="selection.length > 0"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-upload
          ref="upload"
          class="filter-item upload-button"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
        >
          <el-button class="filter-item" type="success" icon="el-icon-plus" style="height: 40px;">
            新增退换货单
          </el-button>
        </el-upload>
        <el-button
          v-if="selection.length > 0"
          class="filter-item"
          type="warning"
          icon="el-icon-document"
          @click="handleExport"
        >
          导出
        </el-button>
      </template>
      
      <template #table-columns>
        <shipping-table-columns
          :show-id="false"
          :show-address="false"
          :show-shipping-info="false"
          :show-package-info="false"
          :show-remark="false"
          @edit="handleUpdate"
          @delete="handleDelete"
        >
          <template #custom-columns>
            <el-table-column label="物流员" prop="created_by_username" align="center" min-width="120">
        <template slot-scope="{row}">
          <span>{{ row.created_by_username || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="CS编号" prop="cs_no" align="center" min-width="150">
        <template slot-scope="{row}">
                <span class="copy-text" @click="copyToClipboard(row.cs_no)">{{ row.cs_no || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="FS编号" prop="fs_no" align="center" min-width="150">
        <template slot-scope="{row}">
                <span class="copy-text" @click="copyToClipboard(row.fs_no)">{{ row.fs_no || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="CW编号" prop="cw_no" align="center" min-width="150">
        <template slot-scope="{row}">
                <span class="copy-text" @click="copyToClipboard(row.cw_no)">{{ row.cw_no || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="供应商" prop="supplier" align="center" min-width="120">
        <template slot-scope="{row}">
          <span>{{ row.supplier || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="CG编号" prop="cg_no" align="center" min-width="150">
        <template slot-scope="{row}">
                <span class="copy-text" @click="copyToClipboard(row.cg_no)">{{ row.cg_no || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="箱数" prop="box_count" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.box_count || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="ID数" prop="id_count" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.id_count || '-' }}</span>
        </template>
      </el-table-column>
            <el-table-column label="处理方式" prop="process" align="center" min-width="120">
        <template slot-scope="{row}">
          <el-tag v-if="row.process === 'IN_PRODUCT'" type="success">入成品仓</el-tag>
          <el-tag v-else-if="row.process === 'REPAIR'" type="warning">回国维修</el-tag>
          <el-tag v-else-if="row.process === 'SCRAP'" type="danger">报废</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
            <el-table-column label="产品ID" prop="product_id" align="center" min-width="150">
        <template slot-scope="{row}">
                <span class="copy-text" @click="copyToClipboard(row.product_id)">{{ row.product_id || '-' }}</span>
        </template>
      </el-table-column>
          </template>
        </shipping-table-columns>
      </template>
    </shipping-table>

    <!-- 编辑退换货单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-form-item label="CS编号" prop="cs_no">
          <el-input v-model="temp.cs_no" placeholder="请输入CS编号" />
        </el-form-item>
        <el-form-item label="FS编号" prop="fs_no">
          <el-input v-model="temp.fs_no" placeholder="请输入FS编号" />
        </el-form-item>
        <el-form-item label="CW编号" prop="cw_no">
          <el-input v-model="temp.cw_no" placeholder="请输入CW编号" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="temp.supplier" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="CG编号" prop="cg_no">
          <el-input v-model="temp.cg_no" placeholder="请输入CG编号" />
        </el-form-item>
        <el-form-item label="箱数" prop="box_count">
          <el-input-number v-model="temp.box_count" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="ID数" prop="id_count">
          <el-input-number v-model="temp.id_count" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="处理方式" prop="process">
          <el-select v-model="temp.process" placeholder="请选择处理方式" style="width: 100%">
            <el-option label="入成品仓" value="IN_PRODUCT" />
            <el-option label="回国维修" value="REPAIR" />
            <el-option label="报废" value="SCRAP" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品ID" prop="product_id">
          <el-input v-model="temp.product_id" placeholder="请输入产品ID" />
        </el-form-item>
        <el-form-item label="创建时间" prop="create_time">
          <el-date-picker
            v-model="temp.create_time"
            type="datetime"
            placeholder="请选择创建时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchAftersaleList, importAftersaleOrder, updateAftersaleOrder, deleteAftersaleOrder, exportAftersaleOrder } from '@/api/shipping'
import ShippingTable from '@/components/ShippingTable'
import ShippingTableColumns from '@/components/ShippingTableColumns'
import { getToken } from '@/utils/auth'

export default {
  name: 'AfterSaleOrder',
  components: { ShippingTable, ShippingTableColumns },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 50,
        process: ''
      },
      multipleSelection: [],
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        cs_no: '',
        fs_no: '',
        cw_no: '',
        supplier: '',
        cg_no: '',
        box_count: 1,
        id_count: 1,
        process: '',
        product_id: '',
        create_time: ''
      },
      rules: {
        cs_no: [{ required: true, message: 'CS编号是必填项', trigger: 'blur' }],
        fs_no: [{ required: true, message: 'FS编号是必填项', trigger: 'blur' }],
        cw_no: [{ required: true, message: 'CW编号是必填项', trigger: 'blur' }],
        box_count: [{ required: true, message: '箱数是必填项', trigger: 'blur' }],
        id_count: [{ required: true, message: 'ID数是必填项', trigger: 'blur' }],
        process: [{ required: true, message: '处理方式是必填项', trigger: 'change' }]
      },
      uploadUrl: process.env.VUE_APP_BASE_API.replace(/['"]/g, '') + '/v1/shipping/aftersale/import',
      uploadHeaders: {
        'Authorization': 'Bearer ' + getToken()
      }
    }
      },
  computed: {
    dialogTitle() {
      return this.dialogStatus === 'create' ? '新增退换货单' : '编辑退换货单'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchAftersaleList(this.listQuery).then(response => {
        this.list = response.results?.data?.items || []
        this.total = response.count || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleProcessChange() {
      this.handleFilter()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('警告：删除后数据将永久丢失，无法恢复！', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
      }).then(() => {
        deleteAftersaleOrder(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录')
        return
      }
      this.$confirm(`警告：删除后数据将永久丢失，无法恢复！`, '批量删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
      }).then(() => {
        const deletePromises = this.multipleSelection.map(item => deleteAftersaleOrder(item.id))
        Promise.all(deletePromises).then(() => {
          this.$message.success('批量删除成功')
          this.getList()
        })
      })
    },
    handleExport() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要导出的记录')
        return
      }
      const ids = this.multipleSelection.map(item => item.id)
      exportAftersaleOrder({ ids }).then(response => {
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '退换货单.xlsx'
        link.click()
        window.URL.revokeObjectURL(url)
        this.$message.success('导出成功')
      })
    },
    handleUploadSuccess(response) {
      if (response.code === 200) {
        this.$message.success('导入成功')
      this.getList()
      } else {
        this.$message.error(response.message || '导入失败')
      }
    },
    handleUploadError() {
      this.$message.error('上传失败')
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('只能上传Excel文件')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }
      return true
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateAftersaleOrder(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message.success('更新成功')
        this.getList()
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        cs_no: '',
        fs_no: '',
        cw_no: '',
        supplier: '',
        cg_no: '',
        box_count: 1,
        id_count: 1,
        process: '',
        product_id: '',
        create_time: ''
      }
    },
    copyToClipboard(text) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success('已复制到剪贴板')
        })
      } else {
        const textArea = document.createElement('textarea')
        textArea.value = text
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        this.$message.success('已复制到剪贴板')
      }
    },
    handlePaginationChange({ page, limit }) {
      this.listQuery.page = page
      this.listQuery.page_size = limit
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/shipping-common.scss';
</style> 